package com.nuoniu.sibanyun.service.crm.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.crm.CrmActivity;
import com.nuoniu.sibanyun.entity.crm.CrmBusiness;
import com.nuoniu.sibanyun.entity.dto.CrmActivityDto;
import com.nuoniu.sibanyun.entity.dto.CrmActivitySearchDto;
import com.nuoniu.sibanyun.entity.vo.CrmActivityVo;
import com.nuoniu.sibanyun.entity.vo.SelectVo;
import com.nuoniu.sibanyun.mapper.crm.CrmActivityMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmFormMapper;
import com.nuoniu.sibanyun.service.crm.ICrmActivityService;
import com.nuoniu.sibanyun.service.crm.ICrmBusinessService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-08-15
 */
@Service
@Log4j2
public class CrmActivityServiceImpl extends ServiceImpl<CrmActivityMapper, CrmActivity> implements ICrmActivityService {

    @Autowired
    private ICrmBusinessService crmBusinessService;
    @Autowired
    private CrmFormMapper formMapper;

    @Override
    public Page<CrmActivity> pageCrmActivity(Page page, CrmActivitySearchDto crmActivitySearchDto) {
        UserInfo userInfo = UserThreadLocal.get();
        Page<CrmActivity> crmActivityPage = baseMapper.pageCrmActivity(page, crmActivitySearchDto,userInfo.getCompanyId());
        return crmActivityPage;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveActivity(CrmActivityDto crmActivityDto) {
        UserInfo userInfo = UserThreadLocal.get();
        LocalDateTime now = LocalDateTime.now();
        CrmActivity crmActivity= new CrmActivity();
        BeanUtils.copyProperties(crmActivityDto, crmActivity);
        if( null == crmActivity.getId()){
            crmActivity.setCompanyId(userInfo.getCompanyId());
            crmActivity.setCompanyName(userInfo.getCompanyName());
            crmActivity.setCreateDate(now);
            crmActivity.setCreateUserId(userInfo.getUserId());
            crmActivity.setCreateUserName(userInfo.getRealName());
        }else{
            boolean owerOrCreater = baseMapper.isOwerOrCreater(userInfo.getUserId(), crmActivity.getId());
            if(!owerOrCreater){
                throw new NuoNiuException("保存失败,你没有修改这条记录的权限");
            }

            formMapper.updateByActivityId(crmActivity);
        }
        crmActivity.setUpdateDate(now);
        crmActivity.setUpdateUserId(userInfo.getUserId());
        crmActivity.setUpdateUserName(userInfo.getRealName());
        boolean save = saveOrUpdate(crmActivity);
        if(!save){
            throw new NuoNiuException("保存失败");
        }
        List<Integer> addBusinessIds = crmActivityDto.getAddBusinessIds();
        List<Integer> deleteBusinessIds = crmActivityDto.getDeleteBusinessIds();
        if(null != addBusinessIds && addBusinessIds.size() > 0){
            crmBusinessService.setActivityAndBusiness(addBusinessIds,crmActivity.getId());
        }
        if(null != deleteBusinessIds && deleteBusinessIds.size() > 0){
            crmBusinessService.clearActivityAndBusinessByBusinessIds(deleteBusinessIds,crmActivity.getId());
        }
    }

    @Override
    public CrmActivityVo detail(Integer id) {
        CrmActivityVo crmActivityVo  = baseMapper.getOne(id);
        List<CrmBusiness> crmBusinesses = crmBusinessService.listActivityBusiness(id);
        crmActivityVo.setBusinessList(crmBusinesses);
        return crmActivityVo;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void batchDelete(List<Integer> ids) {
        UserInfo userInfo = UserThreadLocal.get();
        UpdateWrapper<CrmActivity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",ids);
        updateWrapper.eq("company_id",userInfo.getCompanyId());
        updateWrapper.set("status",1);

        boolean update = update(updateWrapper);
        if(!update){
            log.info("删除市场活动失败,ids:{}",ids);
            throw new NuoNiuException("删除失败");
        }
        // 清空 活动与商机关系
        crmBusinessService.clearActivityAndBusiness(ids);

    }

    @Override
    public boolean checkActivityTitle(Integer id,String activityTitle) {
        if(StringUtils.isBlank(activityTitle)){
            throw new NuoNiuException("活动名称不能为空");
        }
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper queryWrapper = new QueryWrapper();
        if( null != id){
            queryWrapper.ne("id",id);
        }
        queryWrapper.eq("status",0);
        queryWrapper.eq("company_id",userInfo.getCompanyId());
        queryWrapper.eq("activity_title",activityTitle);
        int count = count(queryWrapper);
        return count > 0;
    }

    /**
     * 获取公司 的市场活动
     * @return
     */
    @Override
    public List<SelectVo> listCompanyActivities() {
        UserInfo userInfo = UserThreadLocal.get();
        List<SelectVo> activities = baseMapper.listCompanyActivities(userInfo.getCompanyId());
        return activities;
    }

}
